import { takeLatest } from 'redux-saga';
import { put, select } from 'redux-saga/effects';
import { get, REQUEST_CATE, REQUEST_PRODUCTS, REQUEST_PRODUCT_RESOURCE } from '../service/mz.data.service';
import immutable from 'seamless-immutable';

const pageSizeConst = 15;

function* fetchClassify() {
	const data = yield get(REQUEST_CATE, {});
	if (data) {
		yield put({ type: 'resource/mergeState', payload: { cates: [{ id: 0, name: '全部商品' }].concat(data) } })
	}
}

function* fetchProducts(action) {
	const data = yield get(REQUEST_PRODUCTS, { ...action.payload, pageSize: pageSizeConst });
	let list = yield select(x => x['resource']['list']);
	let end = false;
	if (data) {
		if (data.list) {
			let newList = list;
			if (action.payload.pageNum === 0) {
				list = data.list;
			} else {
				list = list.concat(immutable(data.list));
			}
			end = data.list.length < pageSizeConst;
		}
		yield put({ type: 'resource/mergeState', payload: { list: list, pageNum: action.payload.pageNum, end: end } });
	}
}

function* fetchProductResources(action) {
	const data = yield get(REQUEST_PRODUCT_RESOURCE, action.payload);
	if (data) {
		yield put({ type: 'resource/mergeState', payload: { productResource: data.media, name: data.name, thumbnail: data.thumbnail } })
	}
}

export const resourceSagas = function* () {
	yield takeLatest('resource/fetchClassify', fetchClassify);
	yield takeLatest('resource/fetchProducts', fetchProducts);
	yield takeLatest('resource/fetchProductResource', fetchProductResources);
}
